package com.ljh.lottery.service.impl;

import com.ljh.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.ljh.lottery.common.exception.ServiceException;
import com.ljh.lottery.common.utils.*;
import com.ljh.lottery.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author: Themberfue
 * @date: 2025/4/10 11:01
 * @description:
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    // ! 对于 Redis 里面的 key 需要标准化：为了区分业务，应该给 key 定义前缀：
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_154950909";

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SMSUtil smsUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        // TODO 1. 校验手机号格式
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        // TODO 2. 生成验证码
        String code = CaptchaUtil.getCaptcha(4);

        // TODO 3. 发送验证码
        Map<String, String> phoneCode = Map.of("code", code);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE
                , phoneNumber
                , JacksonUtil.writeValueAsString(phoneCode));

        // TODO 4. 存入 Redis 缓存
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, code, VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        // TODO 1. 校验手机号格式
        if (!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
